package com.darren.euc.action.app;

import com.alibaba.fastjson.JSONArray;
import com.darren.euc.dao.BannerDao;
import com.darren.euc.entity.*;
import com.darren.euc.repository.MeetingRoomRepository;
import com.darren.euc.repository.ProvinceRepository;
import com.darren.euc.repository.SpaceRepository;
import com.darren.euc.service.*;
import com.darren.euc.util.DateUtil;
import com.darren.euc.util.Kv;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

import static com.darren.euc.util.GenegateDomainUtil.generateValidPicUrl;
import static com.darren.euc.util.GenegateDomainUtil.getAppVersion;
import static com.darren.euc.util.GenegateDomainUtil.isAvaliable;

/**
 * app通用接口
 * Created by JUECHENG at 2018/3/12 14:05.
 */
@Controller
@RequestMapping("/_app")
public class _HomeAction {

    @Autowired
    private BannerService bannerService;
    @Autowired
    private ClientService clientService;
    @Autowired
    private SpaceService spaceService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private ProvinceRepository provinceRepository;
    @Autowired
    private CityService cityService;
    @Autowired
    private SuggestService suggestService;
    @Autowired
    private SpaceRepository spaceRepository;

    @Autowired
    private ActivityMemberRelService activityMemberRelService;

    @Autowired
    private MeetingroomOrderService meetingroomOrderService;

    @Autowired
    private MeetingRoomRepository meetingRoomRepository;

    @Autowired
    private BannerDao bannerDao;



    /**
     * 首页数据
     * {轮播，代办事项，精彩活动，最新公告，最新入住，[消息]}
     */
    @ResponseBody
    @RequestMapping(value = "/home")
    public ResponseJSON home(HttpServletRequest request){
        ResponseJSON bean = new ResponseJSON();
        Map data = new HashMap();

        String[] pics = {
            "http://101.200.197.7:9527/pic/a.jpg",
            "http://101.200.197.7:9527/pic/b.jpg",
            "http://101.200.197.7:9527/pic/gg.png",
            "http://101.200.197.7:9527/pic/gg2.png",

            "http://101.200.197.7:9527/pic/mg.jpg",
            "http://101.200.197.7:9527/pic/timg.jpg",
            "http://101.200.197.7:9527/pic/timg2.jpg",
        };
        List banners = bannerService.findAll();
        List todos = Lists.newArrayList();
        List<TODO> Todos = getTodos(request);
        if (Todos != null){
            Todos.forEach(todo -> {
                Map<String,Object> map = Maps.newHashMap();
                map.put("todo_id",todo.getId());
                map.put("title",todo.getTitle());
                map.put("address",todo.getSpaceName());
                map.put("roomName",todo.getRoomName());
                map.put("time",todo.getStartTime());
                map.put("type",todo.getType());
                todos.add(map);
            });
        }

        List<NoticeVO> notices = Lists.newArrayList();


        List clients = clientService.findPage(Kv.of(), 1, 4).getList();
        if(null != clients && clients.size() > 4){
            clients = clients.subList(0,4);
        }

        Kv def_space = Kv.of();
        Member member = (Member) request.getAttribute("member");

        List<ActivityDTO> activities = Lists.newArrayList();
        if (member!= null|| !isAvaliable()){
            Integer spaceId  = member.getSpaceId();
            List<Activity> activs = activityService.findNewTop5(spaceId);
            activities = Lists.newArrayList();
            for (Activity activ :activs ){
            	if((spaceId >=0||activ.getUserAreaId()==0||activ.getIsUnVip()==1)&&activities.size()<5){
            		activities.add(new ActivityDTO(activ));
            	}
            }
            List<Notice> noticeList = noticeService.findNewTop2(spaceId.longValue());
            noticeList.forEach(notice -> notices.add(new NoticeVO(notice)));
        }
        
        if(member== null && isAvaliable()){
        	Integer spaceId  = 0;
            List<Activity> activs = activityService.findAllTop5();
            activities = Lists.newArrayList();
            for (Activity activ :activs ){
            	if(activ.getIsUnVip()==1 &&activities.size()<5){
            		activities.add(new ActivityDTO(activ));
            	}
            }
           // List<Notice> noticeList = noticeService.findNewTop2(spaceId.longValue());
           // noticeList.forEach(notice -> notices.add(new NoticeVO(notice)));
        }

        //已登录会员
        if (member != null|| !isAvaliable()){
            //默认空间
            Integer space_id = member.getSpaceId();
            Space space = spaceService.findById(space_id);
            if (space != null){
                def_space.set("space_id", space.getId()).set("spaceName", space.getSpaceName()).set("provinceName", space.getProvince().getProvinceName());
            }
        }
        if (def_space.size() == 0 || !isAvaliable()){
            PageBean spaces = spaceService.findPage( Kv.of("province_id", 110000),1,1);
            if (spaces.getList().size() > 0){
                Map space = (Map) spaces.getList().get(0);
                def_space.set("space_id", space.get("id"))
                        .set("spaceName", space.get("spaceName"))
                        .set("provinceName", space.get("provinceName"));
            }
        }
        if (isAvaliable()){
            data.put("banners", banners);
            data.put("todos", todos);
            data.put("activities", activities);
            data.put("notices", notices);
            data.put("clients", clients);
            data.put("def_space", def_space);
        }
        return bean.setData(data);
    }

    /**
     * app版本信息
     */
    @ResponseBody
    @RequestMapping(value = "/version")
    public ResponseJSON version(HttpServletRequest request){
        ResponseJSON bean = new ResponseJSON();
        String appVerionDir = request.getSession().getServletContext().getRealPath("upload/app/");
        File file = new File(appVerionDir);
        String[] fileNames = file.list((dir, name) -> {
            if (name != null && name.toLowerCase().endsWith(".apk") && name.contains("release_")) {
                return true;
            } else {
                return false;
            }
        });
        String basePath = request.getScheme() + "://" + request.getServerName();
        String downloadUrl  = basePath + request.getSession().getServletContext().getContextPath()+"/page/anshu_IBC@build_5.7.2.apk";
        String version = getAppVersion();
        if (fileNames != null && fileNames.length > 0){
            String fileName = fileNames[fileNames.length-1];
            downloadUrl = request.getSession().getServletContext().getContextPath()+"/upload/app/" + fileName;
            String tmp = fileName.split("release_")[1];
            tmp=tmp.split("\\.apk")[0];
            version = tmp.split("_")[1];
        }
        Kv res = Kv.of("ios_version", Kv.of("version", "1")
                    .set("note", "1.IOS更新说明1\n2.IOS更新说明2")
                    .set("downloadUrl", "www.baidu.com"))
            .set("android_version", Kv.of("version", version)
                    .set("note", "1.更新说明1\n2.更新说明2")
                    .set("downloadUrl", generateValidPicUrl(downloadUrl))
            );
        return bean.setData(res);
    }

    /**
     * 反馈意见
     * @param content 反馈内容
     */
    @ResponseBody
    @RequestMapping(value = "/feedback")
    public ResponseJSON feedback(HttpServletRequest request,
                                 @RequestParam String content){
        Member member = (Member) request.getAttribute("member");//登录人
        ResponseJSON bean = new ResponseJSON();
        Suggest suggest = new Suggest();
        suggest.setPersonName(member.getName());
        suggest.setContent(content);
        suggest.setUserTel(member.getMobile());
        suggest.setUserAreaId(member.getSpaceId().longValue());
        suggest.setUserArea(member.getBelongSpaceName()!=null?member.getBelongSpaceName():"");
        suggest.setStatus(0);
        suggest.setAddTime(new Date());
        suggest.setModTime(new Date());
        suggest.setResult("");//处理意见设置为空
        return bean.setData(suggestService.save(suggest));
    }

    /**
     * 省份信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/provinces")
    public ResponseJSON provinces(){
        ResponseJSON bean = new ResponseJSON();
        List<Map> list = cityService.findEnableProvinces();

        return bean.setData(list);
    }

    /**
     * 城市信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cities")
    public ResponseJSON cities(@RequestParam(name = "province_id",required = false, defaultValue = "0") Integer province_id){
        ResponseJSON bean = new ResponseJSON();
        Kv kv = Kv.of();
        if (province_id != 0) kv.set("province_id", province_id);

        List<Map> list = cityService.findEnableProvince(kv);
        return bean.setData(list);
    }


    /**
     * banner信息
     * @return
     */
    @RequestMapping(value = "/banner_detail")
    public void bannerDetail(@RequestParam long id, Model model){
        Banner banner = bannerDao.findById(id);
        model.addAttribute("bean", banner);
    }

    private List<TODO> getTodos(HttpServletRequest request){
        Member member = (Member) request.getAttribute("member");
        if (member == null){
            return null;
        }
        Space space = null;
        if (member.getSpaceId()!=null){
            space = spaceRepository.findOne(member.getSpaceId());
        }
        List<ActivityMemberRel> activityMemberRels = activityMemberRelService.findByMemberIdAndStatusIn(member.getId().longValue(),
                Lists.newArrayList(1));
        List<Activity> activityList = Lists.newArrayList();
        if (activityMemberRels.size() >= 0) {
            List<Long> longList = activityMemberRels.stream().map(ActivityMemberRel::getActivityId)
                    .collect(Collectors.toList());
            activityList = activityService.findByIdIn(longList);
        }
        List<MeetingroomOrder> meetingroomOrderList = meetingroomOrderService
                .findBySpaceIdAndStatusAndPayStatusNotAndDayGreaterThanEqual(member.getSpaceId(), 1,0,
                        new DateTime().withMillisOfDay(0).toDate());
        List<MeetingroomOrder> todoOrderList = Lists.newArrayList();
        if (meetingroomOrderList.size() > 0) {
            todoOrderList = meetingroomOrderList.stream().filter(meetingroomOrder -> JSONArray
                    .parseArray(meetingroomOrder.getMemList(), Integer.class).contains(member.getId())).collect(Collectors.toList());
        }
        List<TODO> todos = Lists.newArrayList();
        for (Activity activity : activityList){
        	if(activity.getStatus()!=3){
	            TODO todo = new TODO();
	            todo.setId(activity.getId().intValue());
	            todo.setType(1);
	            todo.setTitle(activity.getTitle());
	            if (space!=null || !isAvaliable()){
	                todo.setSpaceName(space.getSpaceName());
	            }
	            todo.setCount(activityList.size());
	            todo.setDate(new DateTime(activity.getAddTime()).toString("yyyy-MM-dd HH:mm:ss"));
	            todo.setStartTime(new DateTime(activity.getBeginTime()).toString("yyyy-MM-dd HH:mm:ss"));
	            todo.setStartTime(new DateTime(activity.getEndTime()).toString("yyyy-MM-dd HH:mm:ss"));
	            todos.add(todo);
        	}
        }
        for (MeetingroomOrder meetingroomOrder : todoOrderList){
            TODO todo = new TODO();
            Meetingroom meetingroom = meetingRoomRepository.findOne(meetingroomOrder.getRoomId());
            todo.setId(meetingroom.getId());
            todo.setType(2);
            todo.setTitle(meetingroomOrder.getSubject());
            todo.setRoomName(meetingroom.getMeetingroomName());
            if (space!=null || !isAvaliable()){
                todo.setSpaceName(space.getSpaceName());
            }
            todo.setMoney(meetingroomOrder.getMoney().toString());
            todo.setCount(JSONArray.parseArray(meetingroomOrder.getMemList(),Integer.class).size());
            todo.setDate(new DateTime(meetingroomOrder.getDay()).toString("yyyy-MM-dd HH:mm:ss"));
            List<BookTimeRange> timeRanges = JSONArray.parseArray(meetingroomOrder.getRangeList(),BookTimeRange.class);
            if (!CollectionUtils.isEmpty(timeRanges)){
                todo.setStartTime(new DateTime(meetingroomOrder.getDay()).toString("yyyy-MM-dd") + " " + timeRanges.get(0).getTime() + ":00");
                todo.setEndTime(new DateTime(meetingroomOrder.getDay()).toString("yyyy-MM-dd") + " " + DateUtil.addHalfHour(timeRanges.get(timeRanges.size()-1).getTime()) + ":00");
            }
            todo.setFacilities(meetingroom.getOtherFacilities());
            todos.add(todo);
        }
        todos.sort(Comparator.comparing(TODO::getDate).thenComparing(TODO::getStartTime));
        return todos.size()>=2?todos.subList(0,2):todos;
    }

}
